package com.oda.camera;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;

import com.activity.colza.R;
import com.oda.camera.util.LoadImage;
import com.oda.camera.util.PathFile;

import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.opengl.Visibility;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.NavUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class SendActivity extends Activity {
	
	View sendProgress;
	
	/**
	 * Content resolver
	 */
	protected Uri image=null; 
	
	/**
	 * Le fichier
	 */
	private File fichier;
	
	/**
	 * List of image to send
	 */
	private PathFile listeImage;
	
	private int check=0;
	
	static final int DATE_DIALOG_ID = 999;
	
	/**
	 * the view
	 *
	 */
	private View loading;
	private View formSend;
	private EditText hauteur,lieu,_date;
	private DatePicker dpResult;
	private double _longitude,_latitude;
	private ArrayList<String> informations;
	private String [] labels={"hauteur","lieu","date"};
	private int year;
	private int month;
	private int day;
	
	/**
	 * 
	 * @return the paths to file
	 */
	private PathFile init() {
		return new LoadImage().getPictures();
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_send);
		loading=findViewById(R.id.send_status);
		formSend=findViewById(R.id.send_form);
		listeImage=this.init();
		fichier=new File(listeImage.get(0));
		
		hauteur=(EditText) findViewById(R.id.hauteurImage);
		lieu=(EditText) findViewById(R.id.lieuImage);
		_date=(EditText) findViewById(R.id.dateImage);
		//Geolocalisation
		LocationManager locationManager;
        String svcName= Context.LOCATION_SERVICE;
        locationManager= (LocationManager)getSystemService(svcName);
        

        //activation du fournisseur GPS et mis à jours de la position suivant des critères
        //laisser le GPS choisir la meilleur position, mis à jours quant un déplacement sup à 10 m détecter et toutes les 2s
        Criteria criteria=new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        criteria.setPowerRequirement(Criteria.POWER_LOW);
        criteria.setAltitudeRequired(false);
        criteria.setBearingRequired(false);
        criteria.setSpeedRequired(false);
        criteria.setCostAllowed(true);
        String provider= locationManager.getBestProvider(criteria, true);
        
        MylocalListener locationListener=new MylocalListener();
        //Récupère la dernière position trouvée ou à jours
        Location location=locationManager.getLastKnownLocation(provider);
        
        updateWithNewLocation(location);
        
        // mis à jours (fournisseur, tps en mili-seconde, distance en mètre, écouteur)
        locationManager.requestLocationUpdates(provider, 20000, 1, locationListener);
		
		Log.d("TO_SERVER", "Sample image: "+fichier.getAbsolutePath());
		sendProgress = findViewById(R.id.send_status);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.send, menu);
		getActionBar().setDisplayHomeAsUpEnabled(true);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			// This ID represents the Home or Up button. In the case of this
			// activity, the Up button is shown. Use NavUtils to allow users
			// to navigate up one level in the application structure. For
			// more details, see the Navigation pattern on Android Design:
			//
			// http://developer.android.com/design/patterns/navigation.html#up-vs-back
			//
			NavUtils.navigateUpTo(this, new Intent(this,
					ODA_Capture_ctivity.class));
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
	/**
	 * event to send to server
	 * @param v the view
	 */
	public void envoieToserver(View v){		
		formSend.setVisibility(View.GONE);
		loading.setVisibility(View.VISIBLE);
		new TansfertData().execute(fichier.getAbsolutePath());
		
		Log.d("SENDING", "Send image to server");
	}
	
	@SuppressWarnings("deprecation")
	public void setDateTime(View v){
		
		showDialog(DATE_DIALOG_ID);
	}
	
	public void getinfos(){
		informations=new ArrayList<String>();
		informations.add(hauteur.getText().toString());
		informations.add(lieu.getText().toString());
		informations.add(_date.getText().toString());
		Log.d("informations", hauteur.getText().toString()+" "+lieu.getText().toString());
	}
	
	
	/**
	 * Task to Connection
	 * @author zou
	 *
	 */
	public class ServiceConnection extends AsyncTask<String, Void, Boolean>{

		@Override
		protected Boolean doInBackground(String... params) {
			// TODO Auto-generated method stub
			return null;
		}
		
	}
	
	/**
	 * Task to TransfertData <In,..,Out>
	 * @author zou
	 *
	 */
	public class TansfertData extends AsyncTask<String, Void, String>{
		
		protected void onPreExecute() {
			super.onPreExecute();
			
		}

		@Override
		protected String doInBackground(String... params) {
			upload(params[0]);
			return null;
		}
		
		protected void onProgressUpdate(String... progress) {
			
		}
		
		protected void onPostExecute(String response) {
			formSend.setVisibility(View.VISIBLE);
			loading.setVisibility(View.GONE);
			if(check!=0){
				Toast.makeText(getApplicationContext(), "Serveur non trouvé", Toast.LENGTH_LONG).show();
				
			}
			//Log.i("REPONSE", response);
		}
		
	}
	
	public String upload(String path){
		String url="http://192.168.137.26:8080/wsRestImage/rest/colza/upload";
		HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        getinfos();
        
        try {
        	//MultipartEntityBuilder to gather data
        	MultipartEntityBuilder multipartEntity=MultipartEntityBuilder.create();
        	multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        	
        	//Add informations
        	multipartEntity.addPart("file", new FileBody(new File(path)));
        	
        	multipartEntity.addTextBody("hauteur", informations.get(0));
        	multipartEntity.addTextBody("lieu", informations.get(1));
        	multipartEntity.addTextBody("date", informations.get(2));
        	multipartEntity.addTextBody("latitude", _latitude+"");
        	multipartEntity.addTextBody("longitude", _longitude+"");
        	
        	httppost.setEntity(multipartEntity.build());
        	
        	HttpResponse reponse=httpclient.execute(httppost);
        	HttpEntity resEntity=reponse.getEntity();
        	
        	BufferedReader reader = new BufferedReader(new InputStreamReader(resEntity.getContent(), "UTF-8"));
            String sResponse;
            StringBuilder s = new StringBuilder();

            while ((sResponse = reader.readLine()) != null) {
                s = s.append(sResponse);
            }
            //Log.i("test", "Response: " + s);
        	return s.toString();
		} catch (Exception er) {
			Log.e("ERROR",""+er);
			check++;
			return null;
		}

	} 
	
	//update de la position
    private void updateWithNewLocation(Location location){
    	TextView myLocationText = (TextView)findViewById(R.id.myLocation);
    	
    	String locationString= "Aucun emplacement trouvé!!";
    	String addressString="Aucune adresse trouvée";
    	
    	if(location!=null){
    		double lat=location.getLatitude();
    		double lng=location.getLongitude();
    		double alt=location.getAltitude();
    		long time=location.getTime();
    		
    		Date date = new Date(time);
    		DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(getApplicationContext());
    		
    		_date.setText(dateFormat.format(date));
    		locationString ="Latitude: " + lat + "\nLongitude: "+ lng + "\nAltitude: "+alt+"" +
    					"\nTime: "+ dateFormat.format(date);
//    		double latitude= location.getLatitude();
//    		double longitude=location.getLongitude();
    		_latitude=lat;
    		_longitude=lng;
    		//geocodage des information longitude et latitude
    		Geocoder gc=new Geocoder(this,Locale.getDefault());
    		
    		try{
    			List<Address> addresses=gc.getFromLocation(lat, lng, 1);
    			//StringBuilder sb=new StringBuilder();
    			if(addresses.size()>0){
    				Address address = addresses.get(0);
    				
//    				for(int i=0;i< address.getMaxAddressLineIndex();i++){
//    					sb.append(address.getAddressLine(i)).append("\n");
//    				}

    				lieu.setText(address.getLocality());
    			}
    			//addressString=sb.toString();
    		}catch(IOException e){
    			
    		}
    	}
    myLocationText.setText("Votre position courante est :\n\n" + locationString);
    }
	
	//classe responsable du déclachement de update
    final class MylocalListener implements LocationListener{

		
		public void onLocationChanged(Location location) {
			// TODO Auto-generated method stub
			updateWithNewLocation(location);
		}

		@Override
		public void onProviderDisabled(String provider) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onProviderEnabled(String provider) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
			// TODO Auto-generated method stub
			
		}
    	
    }
    
    @Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DATE_DIALOG_ID:
		   // set date picker as current date
		   return new DatePickerDialog(this, datePickerListener, 
                         year, month,day);
		}
		return null;
	}
    
    private DatePickerDialog.OnDateSetListener datePickerListener 
    = new DatePickerDialog.OnDateSetListener() {

    	// when dialog box is closed, below method will be called.
    	public void onDateSet(DatePicker view, int selectedYear,
    			int selectedMonth, int selectedDay) {
    		year = selectedYear;
    		month = selectedMonth;
    		day = selectedDay;

    		// set selected date into textview
    		//_date.setText(day+"/"+month+"/"+year);

    		// set selected date into datepicker also
    		//dpResult.init(year, month, day, null);

    	}
    };
    
  

}
